package com.hoshiicloud.user.service.impl.rbac;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.UsersLoginVO;
import com.hoshiicloud.auth.vo.TokenUsersVO;
import com.hoshiicloud.common.constant.DeleteStatusEnum;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.rbac.entity.SysPermissiones;
import com.hoshiicloud.rbac.entity.SysRoles;
import com.hoshiicloud.user.entity.company.ComUsers;
import com.hoshiicloud.user.entity.company.Company;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.company.ICompanyMapper;
import com.hoshiicloud.user.mapper.rbac.IComUsersMapper;
import com.hoshiicloud.user.service.rbac.IComUsersService;
import com.hoshiicloud.user.service.rbac.ISysPermissionesService;
import com.hoshiicloud.user.service.rbac.ISysRolesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 公司用户基本信息表 服务实现类
 * </p>
 * 2019-04-24
 */
@Service
public class ComUsersServiceImpl extends ServiceImpl<IComUsersMapper, ComUsers> implements IComUsersService {

    private final IdGeneratorService idGeneratorService;
    private final ISysRolesService sysRolesService;
    private final ISysPermissionesService sysPermissionesService;
    private final ICompanyMapper companyMapper;

    public ComUsersServiceImpl(IdGeneratorService idGeneratorService, ISysRolesService sysRolesService,
            ISysPermissionesService sysPermissionesService,
            ICompanyMapper companyMapper) {
        this.idGeneratorService = idGeneratorService;
        this.sysRolesService = sysRolesService;
        this.sysPermissionesService = sysPermissionesService;
        this.companyMapper = companyMapper;
    }


    /**
     * 根据id查询平台信息
     */
    @Cacheable(cacheNames = "companyusers", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Override
    public ComUsers getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * 修改公司用户基本信息
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "companyusers", allEntries = true)
    @Override
    public boolean updateById(ComUsers entity) {

        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改公司用户基本失败"));
        }
        return true;
    }

    @Override
    public UsersLoginVO getComUserLoginDetail(String phone) {

       /* UsersLoginVO rs = new UsersLoginVO()
       if (StringUtils.isBlank(phone)) {
            throw new ServiceException("手机号不能为空");
        }
        ComUsers comUsers = this.getComUsers(phone);
        BeanUtils.copyProperties(comUsers, rs);
        rs.setUsername(comUsers.getPhone());

        *//*获取角色信息*//*
        List<SysRoles> listRoles = sysRolesService.getRolesByUserId(comUsers.getId());
        List<String> listRoleNames = listRoles.stream().map(role -> role.getName()).collect(Collectors.toList());
        rs.setRoleList(listRoleNames);
        List<SysPermissiones> listPem = sysPermissionesService.getSysPermissionesByUserId(comUsers.getId());
        List<String> pemValueList = listPem.stream().filter(per -> StringUtils.isNotBlank(per.getUri()))
                .map(SysPermissiones::getPermissionValue).collect(Collectors.toList());
        rs.setPermissionValueList(pemValueList);
        List<String> urlList = listPem.stream().filter(per -> StringUtils.isNotBlank(per.getUri()))
                .map(SysPermissiones::getUri).collect(Collectors.toList());
        rs.setPermissionUrlList(urlList);
        */
        return new UsersLoginVO();
    }

    /**
     * 新增公司用户基本
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "companyusers", allEntries = true)
    @Override
    public long saveComUsers(ComUsers entity) {
        String id = idGeneratorService.queryGeneratorId();

        if (id == null) {
            throw new ServiceException(CommonError.error("新增公司用户基本失败"));
        }
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setUpdatedTime(LocalDateTime.now());

        /* 设置日期参数 */
        entity.setBirthdayTime(LocalDateTime.now());
        entity.setLastLoginTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增公司用户基本失败"));
        }
        return entity.getId();
    }

    @Override
    public TokenUsersVO getCompanyUserLoginDetail(Map<String, String> map) {
        String phone = map.getOrDefault("username", "");
        String privateDomain = map.getOrDefault("privateDomain", "");
        if (StringUtils.isBlank(phone)) {
            throw new ServiceException("手机号不能为空");
        }
        if (StringUtils.isBlank(privateDomain)) {
            throw new ServiceException("二级域名为空");
        }

        Company company = this.getCompany(privateDomain);
        ComUsers comUsers = this.getComUsers(phone, company.getId());


        /*获取角色信息*/
        List<SysRoles> listRoles = sysRolesService.getRolesByUserId(comUsers.getId());
        List<String> listRoleNames = listRoles.stream().map(SysRoles::getName).collect(Collectors.toList());
        List<SysPermissiones> listPem = sysPermissionesService.getSysPermissionesByUserId(comUsers.getId());
        List<String> pemValueList = new ArrayList<>();
        for (SysPermissiones s : listPem) {
            if (StringUtils.isNotBlank(s.getUri())) {
                pemValueList.add(s.getPermissionValue());
            }
        }
        List<String> urlList = listPem.stream().filter(per -> StringUtils.isNotBlank(per.getUri()))
                .map(SysPermissiones::getUri).collect(Collectors.toList());

        TokenUsersVO rs = new TokenUsersVO();
        rs.setUsername(comUsers.getPhone());
        rs.setRealName(comUsers.getRealName());
        rs.setUserId(comUsers.getId());
        rs.setNickName(comUsers.getNickName());
        rs.setPassword(comUsers.getPassword());
        rs.setAvatar(comUsers.getAvatar());
        rs.setLocked(comUsers.getLocked());
        rs.setCompanyId(company.getId());
        rs.setCompanyName(company.getName());
        rs.setRoleList(listRoleNames);
        rs.setPemValueList(pemValueList);
        rs.setUrlList(urlList);
        return rs;
    }


    private Company getCompany(String privateDomain) {
        QueryWrapper<Company> tq = new QueryWrapper<>();
        tq.lambda().eq(Company::getPrivateDomain, privateDomain);
        Company company = companyMapper.selectOne(tq);
        if (company == null) {
            throw new ServiceException(privateDomain + "二级域名无对应租户");
        }
        return company;
    }

    private ComUsers getComUsers(String phone, Long companyId) {
        QueryWrapper<ComUsers> tq = new QueryWrapper<>();
        tq.lambda().eq(ComUsers::getPhone, phone)
                .eq(ComUsers::getCompanyId, companyId)
                .eq(ComUsers::getDeleted, DeleteStatusEnum.UN_DELETED.getCode());
        ComUsers comUsers = this.getOne(tq);
        if (comUsers == null) {
            throw new ServiceException("用户不存在: " + phone);
        }
        return comUsers;
    }


}
